package org.jeecg.modules.tls.training.trainingManage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.vo.SysUserVo;
import org.jeecg.modules.tls.blog.article.entity.BlogArticle;
import org.jeecg.modules.tls.blog.article.vo.ArticleDetailVo;
import org.jeecg.modules.tls.blog.article.vo.BlogTagVo;
import org.jeecg.modules.tls.blog.article.vo.PageVo;
import org.jeecg.modules.tls.blog.blogarticletag.entity.BlogArticleTag;
import org.jeecg.modules.tls.blog.common.AppHttpCodeEnum;
import org.jeecg.modules.tls.blog.common.ResponseResult;
import org.jeecg.modules.tls.blog.tag.entity.BlogTag;
import org.jeecg.modules.tls.blog.utils.BeanCopyUtils;
import org.jeecg.modules.tls.csmg.cscourse.entity.CsCourse;
import org.jeecg.modules.tls.csmg.cscourse.service.ICsCourseService;
import org.jeecg.modules.tls.csmg.cscourse.vo.CsCourseVo;
import org.jeecg.modules.tls.csmg.viewmodel.admin.CourseRequestVM;
import org.jeecg.modules.tls.training.trainingCourse.entity.TrainingCourse;
import org.jeecg.modules.tls.training.trainingCourse.service.ITrainingCourseService;
import org.jeecg.modules.tls.training.trainingManage.Dto.TrainingDto;
import org.jeecg.modules.tls.training.trainingManage.entity.Course;
import org.jeecg.modules.tls.training.trainingManage.entity.Training;
import org.jeecg.modules.tls.training.trainingManage.mapper.TrainingMapper;
import org.jeecg.modules.tls.training.trainingManage.service.ITrainingService;
import org.jeecg.modules.tls.training.trainingManage.vo.TrainingUserCourseVo;
import org.jeecg.modules.tls.training.trainingManage.vo.TrainingVo;
import org.jeecg.modules.tls.training.trainingUser.entity.TrainingUser;
import org.jeecg.modules.tls.training.trainingUser.service.ITrainingUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 培训表
 * @Author: jeecg-boot
 * @Date:   2023-03-27
 * @Version: V1.0
 */
@Service
public class TrainingServiceImpl extends ServiceImpl<TrainingMapper, Training> implements ITrainingService {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ICsCourseService csCourseService;

    @Autowired
    private ITrainingUserService trainingUserService;

    @Autowired
    private ITrainingCourseService trainingCourseService;

    @Override
    public Result<String> addTraining(TrainingDto trainingDto) {
        String name = trainingDto.getName();
        if (name.isEmpty()){
            return Result.error(508,"请输入培训活动名称");
        }else if(count(Wrappers.<Training>lambdaQuery().eq(Training::getName,name.trim()))>0){
            return Result.error("培训活动已存在");
        }


        long startTime = trainingDto.getStartTime().getTime();
        long endTime = trainingDto.getEndTime().getTime();
        int compare = Long.compare(startTime, endTime);




        if(compare>=0){
            return Result.error(508,"结束时间请大于开始时间");
        }else if(trainingDto.getUserIds() == null || trainingDto.getUserIds().length==0){
            return Result.error(508,"请输入培训用户");
        }

//        else if(trainingDto.getTrainingCourse() == null || trainingDto.getTrainingCourse().isEmpty()){
//            return Result.error(508,"请输入培训课程");
//        }

        Training training = new Training();
        training.setName(trainingDto.getName());
        training.setStartTime(trainingDto.getStartTime());
        training.setEndTime(trainingDto.getEndTime());
        training.setDescription(trainingDto.getDescription());
        training.setTenantId(trainingDto.getTenantId());

        //添加博客
        if(!save(training)){
            return Result.error("培训活动添加失败");
        }

        String[] userIds = trainingDto.getUserIds();
        ArrayList<TrainingUser> trainingUserLists = new ArrayList<>();
        ArrayList<TrainingCourse> trainingCourseLists = new ArrayList<>();
        for(String userId:userIds){
            TrainingUser trainingUser = new TrainingUser();
            trainingUser.setTenantId(trainingDto.getTenantId());
            trainingUser.setTrainingId(training.getId());
            trainingUser.setUserId(userId);
            trainingUserLists.add(trainingUser);
        }

        List<Course> Courses = trainingDto.getTrainingCourse();
        for (Course course :Courses) {
            TrainingCourse trainingCourse = new TrainingCourse();
            trainingCourse.setTenantId(trainingDto.getTenantId());
            trainingCourse.setTrainingId(training.getId());
            trainingCourse.setCourseId(course.getCourseId());
            trainingCourse.setSort(course.getSort());
            trainingCourseLists.add(trainingCourse);
        }
        trainingUserService.saveBatch(trainingUserLists);
        trainingCourseService.saveBatch(trainingCourseLists);
        return Result.ok("添加成功");
    }

    @Override
    public ResponseResult trainingList(String id) {

        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.QUERY_TRAINING_LIST_ERROR);
        }

        Training trainingDetail = getById(id);
        TrainingVo trainingVo = BeanCopyUtils.copyBean(trainingDetail, TrainingVo.class);

        //查询培训用户表的用户id
        QueryWrapper<TrainingUser> queryUserWrapper = new QueryWrapper<>();
        queryUserWrapper.eq("training_id", id);
        List<TrainingUser> trainingUserList = trainingUserService.list(queryUserWrapper);
        //查询培训课程表的课程id
        QueryWrapper<TrainingCourse> queryCourseWrapper = new QueryWrapper<>();
        queryCourseWrapper.eq("training_id", id);
        List<TrainingCourse> trainingCourseList = trainingCourseService.list(queryCourseWrapper);

        //获取关联表的的用户id，并且去重
        List<String> trainingUserIds = trainingUserList.stream()
                .map(trainingUser -> trainingUser.getUserId())
                .collect(Collectors.toList());

        List<SysUser> sysUsers = sysUserService.listByIds(trainingUserIds);


        //bean拷贝
        List<SysUserVo> sysUserVos = new ArrayList<>();
        List<CsCourseVo> csCourseVos = new ArrayList<>();

        for (SysUser user : sysUsers) {
            SysUserVo sysUserVo = new SysUserVo();
            sysUserVo.setUserId(user.getId());
            sysUserVo.setUsername(user.getUsername());
            sysUserVos.add(sysUserVo);
        }
        if (sysUserVos!=null){
            trainingVo.setUsers(sysUserVos);
        }

        for(TrainingCourse trainingCourse:trainingCourseList){

            String courseId = trainingCourse.getCourseId();
            CsCourse csCourse = csCourseService.getById(courseId);
            CsCourseVo csCourseVo = new CsCourseVo();
            csCourseVo.setCourseId(csCourse.getId());
            csCourseVo.setCourseName(csCourse.getName());
            csCourseVo.setSort(trainingCourse.getSort());
            csCourseVos.add(csCourseVo);
        }

        if (csCourseVos!=null){
            trainingVo.setCourses(csCourseVos);
        }

        return ResponseResult.okResult(trainingVo);
    }

    @Override
    public Result<String> editTraining(TrainingDto trainingDto) {

        String id = trainingDto.getId();
        if(id==null){
            return Result.error("请选择培训");
        }

        //修改培训活动
        Training training = BeanCopyUtils.copyBean(trainingDto, Training.class);
        updateById(training);
        String[] userIds = trainingDto.getUserIds();
        List<Course> trainingCourses = trainingDto.getTrainingCourse();
        //如果有id的话先删除
        if(Objects.nonNull(userIds) && userIds.length > 0){
            trainingUserService.remove(Wrappers.<TrainingUser>lambdaQuery().eq(TrainingUser::getTrainingId,training.getId()));
        }

        //如果有id的话先删除
        if(Objects.nonNull(trainingCourses) && trainingCourses.size() > 0){
            trainingCourseService.remove(Wrappers.<TrainingCourse>lambdaQuery().eq(TrainingCourse::getTrainingId,training.getId()));
        }

        ArrayList<TrainingUser> trainingUserLists = new ArrayList<>();
        ArrayList<TrainingCourse> trainingCourseLists = new ArrayList<>();
        for (String userId : userIds) {
            TrainingUser trainingUser = new TrainingUser();
            trainingUser.setTrainingId(training.getId());
            trainingUser.setUserId(userId);
            trainingUserLists.add(trainingUser);
        }


        for (Course course : trainingCourses) {
            TrainingCourse trainingCourse = new TrainingCourse();
            trainingCourse.setTrainingId(training.getId());
            trainingCourse.setCourseId(course.getCourseId());
            trainingCourse.setSort(course.getSort());
            trainingCourseLists.add(trainingCourse);
        }
        //添加 培训和用户的关联
        trainingUserService.saveBatch(trainingUserLists);

        //添加 培训和用户的关联
        trainingCourseService.saveBatch(trainingCourseLists);
        return Result.OK("修改成功");
    }

    @Override
    public ResponseResult queryMyTraining() {
        //获取当前用户id
        Subject subject = SecurityUtils.getSubject();
        LoginUser userNow = (LoginUser) subject.getPrincipal();
        String userNowId = userNow.getId();
        //查询培训用户表的用户id
        QueryWrapper<TrainingUser> queryUserWrapper = new QueryWrapper<>();
        queryUserWrapper.eq("user_id", userNowId);
        List<TrainingUser> myTrainingUsers = trainingUserService.list(queryUserWrapper);

        List<TrainingUserCourseVo> trainingUserCourseVos = new ArrayList<>();
        for (TrainingUser myTraining : myTrainingUsers){
            String trainingId = myTraining.getTrainingId();
            Training training = getById(trainingId);
            TrainingUserCourseVo trainingUserCourseVo = BeanCopyUtils.copyBean(training, TrainingUserCourseVo.class);
            //查询培训课程表的课程id
            QueryWrapper<TrainingCourse> queryCourseWrapper = new QueryWrapper<>();
            queryCourseWrapper.eq("training_id", trainingId);
            List<TrainingCourse> trainingCourseList = trainingCourseService.list(queryCourseWrapper);
            List<CsCourseVo> csCourseVos = new ArrayList<>();
            for(TrainingCourse trainingCourse:trainingCourseList){
                String courseId = trainingCourse.getCourseId();
                CsCourse csCourse = csCourseService.getById(courseId);
                CsCourseVo csCourseVo = new CsCourseVo();
                csCourseVo.setCourseId(csCourse.getId());
                csCourseVo.setCourseName(csCourse.getName());
                csCourseVo.setSort(trainingCourse.getSort());
                csCourseVos.add(csCourseVo);
            }
            trainingUserCourseVo.setCourses(csCourseVos);
            trainingUserCourseVos.add(trainingUserCourseVo);
        }
        PageVo pageVo = new PageVo(trainingUserCourseVos, (long) myTrainingUsers.size());
        return ResponseResult.okResult(pageVo);
    }
}

